//
//  BluetoothManager.m
//  SHHCPhone
//
//  Created by sheng long on 14-6-29.
//  Copyright (c) 2014年 sheng long. All rights reserved.
//

#import "BluetoothManager.h"

//搜索超时
#define TIMEOUT_NUMBER          10

@interface BluetoothManager()<UITableViewDelegate,UITableViewDataSource>
{
    //搜索蓝牙view
    UIView *mainView;
    UITableView *mainTable;
    
    //搜索蓝牙超时计时器
    NSTimer *timeoutTimer;
}

@end

@implementation BluetoothManager

@synthesize CBManager=_CBManager;
@synthesize showInBaseView;
@synthesize peripheralArray;
@synthesize bleModel=_bleModel;

-(void)dealloc
{
    [self stopTimer];
}

-(id)init
{
    self = [super init];
    if (self) {
        
        _bleModel = [[BLEModel alloc] init];
        _bleModel.bluetoothManager = self;
        
        _CBManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    return self;
}

//手动查找设备
-(void)connectCBManager
{
    if (self.CBManager.state == CBCentralManagerStatePoweredOn) {
        //搜索设备中
        _bleModel.isManual = YES;
        [self searchDevice];
        
        //显示搜索页面
        [self showLoadingView];
        
        //超时设置
        [self startTimer];
    }else{
        //打开蓝牙
        _CBManager = nil;
        _CBManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
}

//搜索设备
-(void)searchDevice
{
//    bleModel = nil;
//    peripheralArray = nil;
    
    if (!_bleModel) {
        _bleModel = [[BLEModel alloc] init];
        _bleModel.bluetoothManager = self;
    }
    //搜索蓝牙设备
    [_bleModel.bleManager stopScanning];
    [_bleModel.bleManager startScanningForUUIDString:nil];
}

#pragma mark - CBCentralManagerDelegate
//开始查看服务，蓝牙开启
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            CLog(@"蓝牙已开启");
            break;
        case CBCentralManagerStatePoweredOff:
            CLog(@"蓝牙已关闭");
            break;
        default:
            break;
    }
    CLog(@"蓝牙状态==%d",central.state);
    if (central.state != CBCentralManagerStatePoweredOn) {
        //蓝牙关闭
        [[NSNotificationCenter defaultCenter] postNotificationName:BLUETOOTHMANAGER_LJSBSB object:nil];
    }else{
        //蓝牙打开
        if ([_bleModel.bleManager isConnected] == NO) {
            //没有连接设备
            [self searchDevice];
        }
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:BLUETOOTHMANAGER_STATE_CHANGE object:nil];
}

#pragma mark - 搜索蓝牙页面
//设置数据源
-(void)setPeripheralArray:(NSArray *)pArray
{
    if (pArray.count>0 && mainView) {
        
        //停止超时定时器
        [self stopTimer];
        
        peripheralArray = pArray;
        [LoadingFrameView directlyDisappear];
        
        if (!mainTable) {
            mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.showInBaseView.view.frame.size.width-20, 100)];
            [mainTable setDelegate:self];
            [mainTable setDataSource:self];
            [mainTable setBounces:NO];
            [mainTable setCenter:mainView.center];
            [mainView addSubview:mainTable];
        }
        [mainTable reloadData];
    }
}

//搜索蓝牙中
-(void)showLoadingView
{
    [self.showInBaseView setLeftDrawerViewControllerEnabled:NO];
    
    peripheralArray = nil;
    
    mainView = [[UIView alloc] initWithFrame:self.showInBaseView.view.bounds];
    [self.showInBaseView.view addSubview:mainView];
    
    UIView *bgView = [[UIView alloc] initWithFrame:mainView.bounds];
    [bgView setBackgroundColor:[UIColor blackColor]];
    [bgView setAlpha:.7];
    [mainView addSubview:bgView];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(butt) forControlEvents:UIControlEventTouchUpInside];
    [button setFrame:mainView.bounds];
    [mainView addSubview:button];
    
    [LoadingFrameView showNoBlockingLoadingview:@"搜索蓝牙设备"];
}

-(void)butt
{
    _bleModel.isManual = NO;
    [self closeView];
}

-(void)closeView
{
    [self.showInBaseView setLeftDrawerViewControllerEnabled:YES];
    
    [self stopTimer];
    
    [LoadingFrameView directlyDisappear];
    [mainView removeFromSuperview];
    mainView = nil;
    mainTable = nil;
}

#pragma mark - 超时计时器
-(void)stopTimer
{
    if (timeoutTimer) {
        [timeoutTimer invalidate];
        timeoutTimer = nil;
    }
}

-(void)startTimer
{
    timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:TIMEOUT_NUMBER target:self selector:@selector(timeout) userInfo:nil repeats:NO];
}

-(void)timeout
{
    [self closeView];
    [LoadingFrameView autoDisappearBlockingview:@"暂无可连接设备"];
}

#pragma mark - UITableViewDelegate
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"cell%d",indexPath.section];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    CBPeripheral *peripheral = (CBPeripheral*)[peripheralArray objectAtIndex:indexPath.row];
    if ([[peripheral name] length])
        [[cell textLabel] setText:[peripheral name]];
    else
        [[cell textLabel] setText:@"Peripheral"];
    
    return cell;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return peripheralArray.count;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CBPeripheral *peripheral = (CBPeripheral*)[peripheralArray objectAtIndex:indexPath.row];
    if ([_bleModel.bleManager isConnected] == YES) {
        return;
    }
	if (![peripheral isConnected]) {
        
        assert(peripheral != nil);
		[_bleModel.bleManager connectPeripheral:peripheral];
        
        [self closeView];
        [LoadingFrameView showLabelLoadingview:@"连接中..."];
    }
}


@end
